package leetcode;

import java.util.Stack;

/**
 * 删除链表倒数第N个节点
 */
public class Code001_RemoveNthFromEnd {
    public static class ListNode{
        public int val;
        public ListNode next;
        public ListNode(){}
        public ListNode(int val){this.val = val; }
        public ListNode(int val, ListNode next){this.val = val;this.next = next;}
    }


    public static ListNode removeNthFromEnd(ListNode head, int n) {

        ListNode dummy = new ListNode(0);
        dummy.next = head; // 哑节点
        ListNode cur = dummy;
        int length = getLength(head);
        for(int i = 1; i < length - n + 1; i++){
            cur = cur.next;
        }

        cur.next = cur.next.next; // 删除n节点
        return dummy.next;

    }

    public static int getLength(ListNode head){
        int len = 0;
        while(head != null){
            head = head.next;
            len++;
        }
        return len;
    }

    public static ListNode removeNthFromEnd2(ListNode head, int n){
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        Stack<ListNode> stack = new Stack<>();
        ListNode cur = dummy;
        while(cur != null){
            stack.push(cur);
            cur = cur.next;
        }

        for(int i = 0; i < n; i++){
            stack.pop();
        }
        ListNode prev = stack.peek();
        prev.next = prev.next.next;
        return dummy.next;
    }


    public static void main(String[] args) {
        Stack<ListNode> stack = new Stack<>();
        stack.peek();
    }


}
